\documentclass[11pt]{article}

%% Comment command
\newcommand{\comment}[1]{}

\usepackage{times}

%% Page layout
\oddsidemargin 0pt
\evensidemargin 0pt
\textheight 600pt
\textwidth 469pt
\setlength{\parindent}{0em}
\setlength{\parskip}{1ex}


\begin{document}

\title{CS 213, Fall 2001\\
Malloc Lab: Writing a Dynamic Storage Allocator\\
Assigned: Friday Nov.~2, Due: Tuesday Nov.~20, 11:59PM}

\author{}
\date{}


\maketitle

Cory Williams ({\tt cgw@andrew.cmu.edu}) is the lead person for this
assignment.

\section{Introduction}

In this lab you will be writing a dynamic storage allocator for C
programs, i.e., your own version of the {\tt malloc}, {\tt free} and
{\tt realloc} routines. You are encouraged to explore the design space
creatively and implement an allocator that is correct, efficient and
fast.

\section{Logistics}

You may work in a group of up to two people. Any clarifications and
revisions to the assignment will be posted on the course Web page.

\section{Hand Out Instructions}

\begin{quote}
\bf SITE-SPECIFIC: Insert a paragraph here that explains how students
should download the {\tt malloclab-handout.tar} file.
\end{quote}

Start by copying \texttt{malloclab-handout.tar} to a protected directory
in which you plan to do your work.  Then give the command:
\verb@tar xvf malloclab-handout.tar@.  This will cause a number of files
to be unpacked into the directory.  The only file you will be
modifying and handing in is {\tt mm.c}.  The {\tt mdriver.c} program
is a driver program that allows you to evaluate the performance of
your solution. Use the command \verb@make@ to generate the driver code
and run it with the command \verb@./mdriver -V@. (The {\tt -V} flag
displays helpful summary information.)

Looking at the file {\tt mm.c} you'll notice a C structure {\tt team}
into which you should insert the requested identifying information
about the one or two individuals comprising your programming team.
{\bf Do this right away so you don't forget.}

When you have completed the lab, you will hand in only one file ({\tt
mm.c}), which contains your solution.

\section{How to Work on the Lab}

Your dynamic storage allocator will consist of the following four
functions, which are declared in {\tt mm.h} and defined in
{\tt mm.c}.

\begin{verbatim}
    int   mm_init(void);
    void *mm_malloc(size_t size);
    void  mm_free(void *ptr);
    void *mm_realloc(void *ptr, size_t size);
\end{verbatim}
The {\tt mm.c} file we have given you implements the simplest but
still functionally correct malloc package that we could think
of. Using this as a starting place, modify these functions (and
possibly define other private {\tt static} functions), so that they
obey the following semantics:

\begin{itemize}
\item {\tt mm\_init:} Before calling {\tt mm\_malloc} {\tt
mm\_realloc} or {\tt mm\_free}, the application program (i.e., the
trace-driven driver program that you will use to evaluate your
implementation) calls {\tt mm\_init} to perform any necessary
initializations, such as allocating the initial heap area.
The return value should be -1 if there was a problem in performing the
initialization, 0 otherwise.
  
\item {\tt mm\_malloc:} The {\tt mm\_malloc} routine returns a pointer
to an allocated block payload of at least {\tt size} bytes.  The
entire allocated block should lie within the heap region and should
not overlap with any other allocated chunk.

We will comparing your implementation to the version of {\tt malloc}
supplied in the standard C library ({\tt libc}). Since the 
{\tt libc} malloc always returns payload pointers that are 
aligned to 8 bytes, your malloc implementation should do likewise
and always return 8-byte aligned pointers.
  
\item {\tt mm\_free:} The {\tt mm\_free} routine frees the block
pointed to by {\tt ptr}.  It returns nothing. This routine is only
guaranteed to work when the passed pointer ({\tt ptr}) was returned by
an earlier call to {\tt mm\_malloc} or {\tt mm\_realloc} and has not
yet been freed.

\item {\tt mm\_realloc:} The {\tt mm\_realloc} routine returns a pointer
to an allocated region of at least {\tt size} bytes  with the following 
constraints. 

\begin{itemize}
\item if {\tt ptr} is NULL, the call is equivalent to {\tt mm\_malloc(size)}; 

\item if {\tt size} is equal to zero, the call is equivalent to 
{\tt mm\_free(ptr)};

\item if {\tt ptr} is not NULL, it must have been returned by an
earlier call to {\tt mm\_malloc} or {\tt mm\_realloc}. The call to
{\tt mm\_realloc} changes the size of the memory block pointed to by
{\tt ptr} (the {\em old block}) to {\tt size} bytes and returns the
address of the new block. Notice that the address of the new block
might be the same as the old block, or it might be different,
depending on your implementation, the amount of internal fragmentation
in the old block, and the size of the {\tt realloc} request.

The contents of the new block are the same as those of the old {\tt
ptr} block, up to the minimum of the old and new sizes. Everything
else is uninitialized. For example, if the old block is 8 bytes and
the new block is 12 bytes, then the first 8 bytes of the new block
are identical to the first 8 bytes of the old block and the last 4
bytes are uninitialized.  Similarly, if the old block is 8 bytes and
the new block is 4 bytes, then the contents of the new block are
identical to the first 4 bytes of the old block.
\end{itemize}
\end{itemize}

These semantics match the the semantics of the corresponding
{\tt libc} {\tt malloc}, {\tt realloc}, and {\tt free} routines.
Type {\tt man malloc} to the shell for complete documentation.

\section{Heap Consistency Checker}  

Dynamic memory allocators are notoriously tricky beasts to program
correctly and efficiently. They are difficult to program correctly
because they involve a lot of untyped pointer manipulation.  You will
find it very helpful to write a heap checker that scans the heap and
checks it for consistency.

Some examples of what a heap checker might check are:
\begin{itemize}
\item Is every block in the free list marked as free?
\item Are there any contiguous free blocks that somehow escaped
coalescing?
\item Is every free block actually in the free list?
\item Do the pointers in the free list point to valid free blocks?
\item Do any allocated blocks overlap?
\item Do the pointers in a heap block point to valid heap
addresses?
\end{itemize}

Your heap checker will consist of the function {\tt int
mm\_check(void)} in {\tt mm.c}.  It will check any invariants or
consistency conditions you consider prudent.  It returns a nonzero
value if and only if your heap is consistent.  You are not limited to
the listed suggestions nor are you required to check all of them.  You
are encouraged to print out error messages when {\tt mm\_check} fails.

This consistency checker is for your own debugging during development.
When you submit {\tt mm.c}, make sure to remove any calls to {\tt
mm\_check} as they will slow down your throughput.  Style points will
be given for your {\tt mm\_check} function. Make sure to put in
comments and document what you are checking.


\section{Support Routines}
The {memlib.c} package simulates the memory system for your
dynamic memory allocator. You can invoke the following functions
in {\tt memlib.c}:

\begin{itemize}
\item {\tt void *mem\_sbrk(int incr)}:   
Expands the heap by {\tt incr} bytes, where {\tt incr} is a positive
non-zero integer and returns a generic pointer to the first byte of
the newly allocated heap area. The semantics are identical to the Unix
{\tt sbrk} function, except that {\tt mem\_sbrk} accepts only a
positive non-zero integer argument.

\item {\tt void *mem\_heap\_lo(void)}:
Returns a generic pointer to the first byte in the heap.

\item {\tt void *mem\_heap\_hi(void)}:
Returns a generic pointer to the last byte in the heap.

\item {\tt size\_t mem\_heapsize(void)}:
Returns the current size of the heap in bytes.

\item {\tt size\_t mem\_pagesize(void)}:
Returns the system's page size in bytes (4K on Linux systems).

\end{itemize}

\section{The Trace-driven Driver Program}

The driver program {\tt mdriver.c} in the {\tt malloclab-handout.tar}
distribution tests your {\tt mm.c} package for correctness, space
utilization, and throughput. The driver program is controlled by a set
of {\em trace files} that are included in the {\tt
malloclab-handout.tar} distribution. Each trace file contains a
sequence of allocate, reallocate, and free directions that instruct
the driver to call your {\tt mm\_malloc}, {\tt mm\_realloc}, and {\tt
mm\_free} routines in some sequence. The driver and the trace files
are the same ones we will use when we grade your handin {\tt mm.c}
file.

The driver {\tt mdriver.c} accepts the following command line arguments:
\begin{itemize}

\item {\tt -t <tracedir>}:
Look for the default trace files in directory {\tt tracedir} 
instead of the default directory defined in {\tt config.h}.

\item {\tt -f <tracefile>}:  
Use one particular {\tt tracefile} for testing instead of the 
default set of tracefiles.

\item {\tt -h}:
Print a summary of the command line arguments.

\item {\tt -l}:
Run and measure {\tt libc} malloc in addition to the student's malloc package.

\item {\tt -v}:  
Verbose output. Print a performance breakdown for each tracefile
in a compact table.

\item {\tt -V}: 
More verbose output. Prints additional diagnostic information as each
trace file is processed.  Useful during debugging for determining
which trace file is causing your malloc package to fail.

\end{itemize}


\section{Programming Rules}
\begin{itemize}
\item You should not change any of the interfaces in {\tt mm.c}.

\item You should not invoke any memory-management related library
calls or system calls.  This excludes the use of {\tt malloc}, {\tt
calloc}, {\tt free}, {\tt realloc}, {\tt sbrk}, {\tt brk} or any
variants of these calls in your code.

\item 
You are not allowed to define any global or {\tt static} compound data
structures such as arrays, structs, trees, or lists in your {\tt mm.c}
program.  However, you {\em are} allowed to declare global scalar variables
such as integers, floats, and pointers in {\tt mm.c}. 

\item
For consistency with the {\tt libc} {\tt malloc} package, which
returns blocks aligned on 8-byte boundaries, your allocator must
always return pointers that are aligned to 8-byte boundaries.  The
driver will enforce this requirement for you.

\end{itemize}

\section{Evaluation}

You will receive {\bf zero points} if you break any of the rules or
your code is buggy and crashes the driver.  Otherwise, your grade will
be calculated as follows:

\begin{itemize}

\item {\em Correctness (20 points).} You will receive full points if your
solution passes the correctness tests performed by the driver program.
You will receive partial credit for each correct trace.

\item {\em Performance (35 points).}  Two performance metrics will be used
to evaluate your solution:

\begin{itemize}
\item {\it Space utilization}: The peak ratio between the aggregate
amount of memory used by the driver (i.e., allocated via
{\tt mm\_malloc} or {\tt mm\_realloc} but not yet freed via
{\tt mm\_free}) and the size of the heap used by your allocator. The
optimal ratio equals to 1.  You should find good policies to minimize
fragmentation in order to make this ratio as close as possible to the
optimal.

\item
{\it Throughput}: The average number of operations completed per second.
\end{itemize}

The driver program summarizes the performance of your
allocator by computing a {\em performance index}, $P$, which is a
weighted sum of the space utilization and throughput
\begin{displaymath}
P = w{U} + (1-w) \min\left(1, \frac{T}{T_{libc}}\right) 
\end{displaymath}
where $U$ is your space utilization, $T$ is your throughput, and
$T_{libc}$ is the estimated throughput of {\tt libc} malloc on your
system on the default traces.\footnote{The value for $T_{libc}$ is a
constant in the driver (600 Kops/s) that your instructor established
when they configured the program.}
The performance index favors space utilization over throughput, with a
default of $w = 0.6$.

Observing that both memory and CPU cycles are expensive system
resources, we adopt this formula to encourage balanced optimization of
both memory utilization and throughput.  Ideally, the performance
index will reach \( P = w + (1-w) = 1\) or \( 100\% \).  Since each
metric will contribute at most $w$ and $1-w$ to the performance index,
respectively, you should not go to extremes to optimize either the
memory utilization or the throughput only. To receive a good score,
you must achieve a balance between utilization and throughput.

\item {Style (10 points).}
\begin{itemize}
\item 
Your code should be decomposed into functions and use 
as few global variables as possible.
\item 
Your code should begin with a header comment that describes the
structure of your free and allocated blocks, the organization of the
free list, and how your allocator manipulates the free list.  each
function should be preceeded by a header comment that describes what
the function does.
\item 
Each subroutine should have a header comment that describes
what it does and how it does it.
\item 
Your heap consistency checker {\tt mm\_check} should be
thorough and well-documented.
\end{itemize}
You will be awarded 5 points for a good heap consistency checker
and 5 points for good program structure and comments.
\end{itemize}

\section{Handin Instructions}

\begin{quote}
\bf SITE-SPECIFIC: Insert a paragraph here that explains how the students
should hand in their solution {\tt mm.c} files.
\end{quote}

\comment{
You will handin your {\tt mm.c} file via a web interface.  See the lab
webpage for details on how to do this.

You may submit your solution for testing as many times as you wish
up until the due date.  The web page will list both your best scoring
submission and your most recent submission.

When you are satisfied with your solution, then you can offically hand
it in.  Only the last version you submit will be graded.

When testing your files locally, make sure to use one of the fish
machines. This will insure that the grade you get from {\tt mdriver}
is representative of the grade you will receive when you submit your
solution.
}

\section{Hints}
\begin{itemize}

\item {\em Use the {\tt mdriver} {\tt -f} option.}  During initial
development, using tiny trace files will simplify debugging and
testing. We have included two such trace files ({\tt
short{1,2}-bal.rep}) that you can use for initial debugging.

\item {\em Use the {\tt mdriver} {\tt -v} and {\tt -V} options.}  The
{\tt -v} option will give you a detailed summary for each trace file.
The {\tt -V} will also indicate when each trace file is read, which 
will help you isolate errors.

\item {\em Compile with {\tt gcc -g} and use a debugger.} A debugger
will help you isolate and identify out of bounds memory references.

\item {\em Understand every line of the malloc implementation in the
textbook.}  The textbook has a detailed example of a simple allocator
based on an implicit free list. Use this is a point of departure.
Don't start working on your allocator until you understand everything
about the simple implicit list allocator.

\item {\em Encapsulate your pointer arithmetic in C preprocessor
macros.}  Pointer arithmetic in memory managers is confusing and error-prone
because of all the casting that is necessary. You can reduce the
complexity significantly by writing macros for your pointer operations.
See the text for examples. 

\item {\em Do your implementation in stages.}  The first 9 traces
contain requests to {\tt malloc} and {\tt free}.  The last 2 traces
contain requests for {\tt realloc}, {\tt malloc}, and {\tt free}. We
recommend that you start by getting your {\tt malloc} and {\tt free}
routines working correctly and efficiently on the first 9 traces. Only
then should you turn your attention to the {\tt realloc}
implementation.  For starters, build {\tt realloc} on top of your
existing {\tt malloc} and {\tt free} implementations. But to get
really good performance, you will need to build a stand-alone {\tt
realloc}.

\item{\em Use a profiler.} You may find the {\tt gprof} tool helpful
for optimizing performance.

\item {\em Start early!} It is possible to write an efficient malloc
package with a few pages of code. However, we can guarantee that it
will be some of the most difficult and sophisticated code you have
written so far in your career. So start early, and good luck!

\end{itemize}
\end{document}






